/**
 * 
 */
package com.mycom.common.base;

import com.alibaba.fastjson.JSONObject;
import com.mycom.common.jdbc.JdbcDao;
import com.mycom.common.jdbc.MongoDao;
import com.mycom.common.utils.ClientCustomSSL;
import com.mycom.common.utils.DateUtil;
import com.mycom.common.utils.DoubleUtil;
import com.mycom.common.utils.IDUtil;
import com.mycom.common.wxpay.PayCnst;
import com.mycom.common.wxpay.WXPayConstants;
import com.mycom.common.wxpay.WXPayUtil;
import com.mycom.common.wxpay.WdPayBase;
import com.mycom.common.wxpay.util.MessageUtil;
import com.mycom.wxTest.RedPkgDetail;
import com.mycom.wxTest.WxWdArgs;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public abstract class AbstractService {
	private static final Logger log = LoggerFactory.getLogger(AbstractService.class);

	@Autowired
	protected JdbcDao jdbcDao;

	@Autowired
	protected MongoDao mongoDao;


	/**验证记录是否重复 true: 重复  false:不重复 */
	protected boolean checkRecordRepeat(String f_record_id) {
		String sql = "select count(*) from lottery.redPkgDetail where f_record_id=?";
		int count = jdbcDao.queryForSimpleObject(sql, new Object[]{f_record_id}, Integer.class);

		return count > 0;
	}

	/** ============================ 微信提现模块 ============================ */

	/**
	 * 微信提交转账
	 *
	 * @throws Exception
	 */
	protected JSONObject commitWxWd(WxWdArgs wxWdArgs) throws Exception {
		JSONObject json = new JSONObject();
		json.put("result", false);

		JSONObject mJson  = doWxWithdrawals(wxWdArgs);

		JSONObject wdResultInfo = mJson.getJSONObject("xml");
		if (wdResultInfo.getString("return_code").equals("SUCCESS")
				&& wdResultInfo.getString("result_code").equals("SUCCESS")) {
			String payment_no   = wdResultInfo.getString("payment_no");
			String payment_time = wdResultInfo.getString("payment_time");

			json.put("payment_no", payment_no);
			json.put("payment_time", payment_time);
			json.put("result", true);
			log.info("微信发送红包成功!, wdResultInfo: " + wdResultInfo);

			return json;
		} else {
			String err_code = wdResultInfo.getString("err_code");
			String err_code_des = wdResultInfo.getString("err_code_des");

			if (err_code.equals("SYSTEMERROR")) { // 系统错误，请重试
				return commitWxWd(wxWdArgs);
			}

			json.put("err_code_des", err_code_des);
			log.warn("微信发送红包失败!, wdResultInfo: " + wdResultInfo);

			return json;
		}
	}

	/**
	 * 将记录参数转化为微信提现参数
	 * @return
	 */
	private WxWdArgs genWxWdArgs(RedPkgDetail redPkgDetail) {
		int payAmountCent = Math.abs((int)DoubleUtil.mul(redPkgDetail.money, WdPayBase.CENT_RATIO));

		WxWdArgs wdArgs = new WxWdArgs();
		String gameId = redPkgDetail.gameId;
		getGameWxCfg(gameId, wdArgs);

		wdArgs.setNonce_str(redPkgDetail.out_trade_no);
		wdArgs.setPartner_trade_no(redPkgDetail.out_trade_no);
		wdArgs.setOpenid(redPkgDetail.openid);
		wdArgs.setAmount(String.valueOf(payAmountCent));
		wdArgs.setSpbill_create_ip(redPkgDetail.ip);

		return wdArgs;
	}

	private WxWdArgs getGameWxCfg (String gameId, WxWdArgs wdArgs) {
		String wxPublicName = WdPayBase.gameWxPublic.get(gameId);
		if (PayCnst.wxPublicName_Haoyun.equals(wxPublicName)) {
			// 好运棋牌
			wdArgs.setMch_appid(WdPayBase.Haoyun.appid);
			wdArgs.setMchid(WdPayBase.Haoyun.mch_id);
			wdArgs.setDesc(WdPayBase.Haoyun.desc);
			wdArgs.setWeb_key(WdPayBase.Haoyun.web_key);
			wdArgs.setCert_file_path(WdPayBase.Haoyun.cert_file_path);
		} else if (PayCnst.wxPublicName_GuanDan.equals(wxPublicName)) {
			// 掼蛋
			wdArgs.setMch_appid(WdPayBase.GuanDan.appid);
			wdArgs.setMchid(WdPayBase.GuanDan.mch_id);
			wdArgs.setDesc(WdPayBase.GuanDan.desc);
			wdArgs.setWeb_key(WdPayBase.GuanDan.web_key);
			wdArgs.setCert_file_path(WdPayBase.GuanDan.cert_file_path);
		} else {
			// 比鸡
			wdArgs.setMch_appid(WdPayBase.BiJi.appid);
			wdArgs.setMchid(WdPayBase.BiJi.mch_id);
			wdArgs.setDesc(WdPayBase.BiJi.desc);
			wdArgs.setWeb_key(WdPayBase.BiJi.web_key);
			wdArgs.setCert_file_path(WdPayBase.BiJi.cert_file_path);
		}

		wdArgs.setCheck_name(WdPayBase.check_name);

		return wdArgs;
	}

	/**
	 * 向微信提交代理商提现订单, 返回提现结果
	 *
	 * @return /**
	 * mJson:
	 * {
	 * "xml":
	 * {
	 * 		"nonce_str":"2f2ed6a2e66d40c5b6c51a928e6a0ac7",
	 * 		"partner_trade_no":"2f2ed6a2e66d40c5b6c51a928e6a0ac7",
	 * 		"payment_time":"2017-09-21 15:00:02",
	 * 		"payment_no":"1000018301201709210019096240",
	 * 		"return_msg":"",
	 * 		"result_code":"SUCCESS",
	 * 		"return_code":"SUCCESS"
	 * }
	 * }
	 * @throws
	 */
	private JSONObject doWxWithdrawals(WxWdArgs wxWdArgs) throws Exception {
		Map<String, String> map = new HashMap<>();
		map.put("mch_appid", wxWdArgs.mch_appid);
		map.put("mchid", wxWdArgs.mchid);
		map.put("nonce_str", wxWdArgs.nonce_str);
		map.put("partner_trade_no", wxWdArgs.partner_trade_no);
		map.put("openid", wxWdArgs.openid);
		map.put("check_name", wxWdArgs.check_name);
		map.put("amount", wxWdArgs.amount);
		map.put("desc", wxWdArgs.desc);
		map.put("spbill_create_ip", wxWdArgs.spbill_create_ip);

		String sign = WXPayUtil.generateSignature(map, wxWdArgs.web_key, WXPayConstants.SignType.MD5);

		wxWdArgs.setSign(sign);
		String xml = MessageUtil.payParametersToXml(wxWdArgs);
		xml = xml.replace("__", "_");
		String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
		String xmlResult = ClientCustomSSL.wxWithdrawalsPost(wxWdArgs.mchid, wxWdArgs.cert_file_path, url, xml);

		org.json.JSONObject iJson = XML.toJSONObject(xmlResult);
		JSONObject mJson = JSONObject.parseObject(iJson.toString());

		return mJson;
	}

	/* ================================== 远程发送红包 =============================== */
	/**
	 * 发送红包接口
	 * @return
	 */
	public JSONObject rmtSendRedPkg(RedPkgDetail redPkgDetail) {
		JSONObject json = new JSONObject();
		json.put("result", false);

		JSONObject jo;
		WxWdArgs wxWdArgs = genWxWdArgs(redPkgDetail);
		try {
			if ((jo = commitWxWd(wxWdArgs)).getBoolean("result")) {
				redPkgDetail.setPayment_no(jo.getString("payment_no"));
				redPkgDetail.setPayment_time(jo.getString("payment_time"));
				redPkgDetail.setTransState(PayCnst.transState_success);
			} else {
				String err_code_des = jo.getString("err_code_des");
				redPkgDetail.setErr_code_des(err_code_des);
				redPkgDetail.setTransState(PayCnst.transState_fail);
			}
		} catch (Exception e) {
			log.warn("红包发放异常: " + e);
			json.put("fAward", PayCnst.no_get_award);

			return json;
		}

		json.put("result", true);
		json.put("redPkgDetail", redPkgDetail);
		log.info("redPkgDetail: " + JSONObject.toJSONString(redPkgDetail));

		return json;
	}

	protected RedPkgDetail genRedPkgDetail(String f_record_id, double money, String openid, String ip, String gameId) {
		RedPkgDetail redPkgDetail = new RedPkgDetail();
		String out_trade_no = IDUtil.gen("");

		redPkgDetail.setF_record_id(f_record_id);
		redPkgDetail.setOut_trade_no(out_trade_no);
		redPkgDetail.setMoney(money);
		redPkgDetail.setOpenid(openid);
		redPkgDetail.setIp(ip);
		redPkgDetail.setGameId(gameId);

		// 默认状态：转账中
		redPkgDetail.setTransState(PayCnst.transState_ongoing);
		redPkgDetail.setPayment_time(DateUtil.getSystemDate());

		return redPkgDetail;
	}

	/*=========================== 微信转账 ============================*/
	public JSONObject wxTransTest() throws Exception {
		String ranStr = IDUtil.gen("");
		String openid = "ozJ021UabznaXIRWWM4qOg9uqxtU";
		String payAmountCent = "100";
		String ip = "180.111.240.46";

		WxWdArgs wxWdArgs = new WxWdArgs();
		wxWdArgs.setMch_appid(WdPayBase.GuanDan.appid);
		wxWdArgs.setMchid(WdPayBase.GuanDan.mch_id);
		wxWdArgs.setNonce_str(ranStr);
		wxWdArgs.setPartner_trade_no(ranStr);
		wxWdArgs.setOpenid(openid);
		wxWdArgs.setCheck_name(WdPayBase.check_name);
		wxWdArgs.setAmount(payAmountCent);
		wxWdArgs.setDesc(WdPayBase.GuanDan.desc);
		wxWdArgs.setSpbill_create_ip(ip);

		JSONObject mJson = doWxWithdrawals(wxWdArgs);

		return mJson;
	}

}
